package com.cevent.gateway.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * @author cevent
 * @create 2024/12/4 9:34
 */
@SpringBootApplication
@EnableEurekaClient
public class GatewayApp {
    private static final Logger LOG= LoggerFactory.getLogger(GatewayApp.class);
    public static void main(String[] args) {
        SpringApplication app=new SpringApplication(GatewayApp.class);
        Environment env=app.run(args).getEnvironment();
        LOG.info("启动成功");
        LOG.info("Gateway启动地址：\t http://127.0.0.1:{}",env.getProperty("server.port"));
    }

    //CORS跨域处理
    @Bean
    public CorsWebFilter corsWebFilter(){
        CorsConfiguration corsConfiguration=new CorsConfiguration();
        corsConfiguration.setAllowCredentials(Boolean.TRUE);
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedHeader("*");
        //注意springboot新版本取消了addAllowedOrigin，要使用addAllowedOriginPattern
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource corsConfigurationSource=new UrlBasedCorsConfigurationSource(new PathPatternParser());
        corsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
        //返回跨域对象
        return new CorsWebFilter(corsConfigurationSource);
    }
}
